package com.geese.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.geese.common.PropertiesService;
import com.geese.common.constants.ResponseConstants;
import com.geese.common.util.JSONUtil;

/**
 * Created by Z先生 on 2017/2/23.
 */
@ControllerAdvice
public class MyExceptionHandler {
	
	private static Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
	
	private static final String CODE_REGEX = "^([1-9])\\d{5}$";
	@Autowired
	private PropertiesService propertiesService;
	
	
	@ExceptionHandler(value = { BusinessException.class })
	@ResponseBody
	public String handleException(BusinessException e) {
		ErrorResult errorResult = getErrorResult(e.getCode());
		return JSONUtil.objectToJson(errorResult);
	}
	
	@ExceptionHandler(value = { UnauthorizedException.class })
	@ResponseBody
	public String handleException(UnauthorizedException e) {
		ErrorResult errorResult = getErrorResult(ResponseConstants.PERMISSION_INSUFFICIENT);
		return JSONUtil.objectToJson(errorResult);
	}
	
	
	@ExceptionHandler(value = { Exception.class })
	@ResponseBody
	public String handleCustomException(Exception e) {
		ErrorResult errorResult = getErrorResult(ResponseConstants.SYSTEM_BUSY);
        logger.error("unknown error", e);
		return JSONUtil.objectToJson(errorResult);
	}
	
	private ErrorResult getErrorResult(int code) {
		int errCode = code;
		boolean flag = isInfoCode(errCode);
		if(!flag) {
			errCode = ResponseConstants.SYSTEM_BUSY;
		}
		return new ErrorResult(errCode, propertiesService.getProperty(String.valueOf(errCode)));
	}
	
	private boolean isInfoCode(int code) {
		String tempCode = String.valueOf(code);
    	if(tempCode.length() != 6) {
    		return false;
    	}
    	return tempCode.matches(CODE_REGEX);
	}

}
